package com.jic.purchase.service.impl;
import java.util.List;

import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.purchase.constant.consist.ResponseCode;
import com.jic.purchase.exception.AppRuntimeException;
import com.jic.purchase.mapper.*;
import com.jic.purchase.model.entity.*;
import com.jic.purchase.model.vo.request.PurchaseContractRequest;
import com.jic.purchase.model.vo.request.UpdatePurchaseContractRequest;
import com.jic.purchase.model.vo.response.QueryInfoPurchaseContractResponse;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.annotation.Resource;

import com.jic.purchase.service.PurchaseContractService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

/**
 * 接口实现类
 *
 * @author : 建投数据科技(山东)有限公司
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class PurchaseContractServiceImpl implements PurchaseContractService {

	@Resource
	private PurchaseContractMapper mapper;

	@Resource
    private ContractAnnexMapper contractAnnexMapper;

	@Resource
    private ContractCostMapper contractCostMapper;

	@Resource
    private ContractPersonMapper contractPersonMapper;

	@Resource
    private ContractStoreMapper contractStoreMapper;


	/**
	 * 新增记录
	 *
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存成功
	 */
	@Override
	public Long save(PurchaseContract request) {
	 int flag = mapper.insert(request);
	 if (flag == 1) {
	   return request.getId();
	 }else {
	   throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
	 }
	}


	/**
	 * 保存或修改记录信息
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存或修改成功
	 * author 建投数据科技(山东)有限公司
	 * @date 2020-3-11 20:54:09
	 */
	@Override
	public int saveOrUpdate(PurchaseContract request){
		log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
		try {
			if (request == null) {
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
			}
			if (request.getId() != null) {
				log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
				int flag = mapper.updateByPrimaryKey(request);
				if(flag == 1){
				  return 1;
				}
			}else{
				log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
				int flag = mapper.insertSelective(request);
				if(flag == 1){
				  return 1;
				}else{
				  throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改失败");
				}
			}
		} catch (Exception e) {
			log.error("用户保存或修改失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
		}
	     return -1;
	}

	/**
	 * 删除记录
	 *
	 * @return int 是否删除成功
	 */
	@Override
	public int deleteByPrimaryKey(PurchaseContract request) {
		int flag = mapper.deleteByPrimaryKey(request.getId());
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
	    }
	}


	/**
	 * 逻辑删除记录
	 *
	 * @param request 含有主键的逻辑删除实体类
	 * @return int 是否逻辑删除成功
	 */
	@Override
	public int deleteByPrimaryKeyLogically(PurchaseContract request) {
		request.setDeleteFlag(1);
		int flag = mapper.updateByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
	    }
	}


	/**
	 * 修改
	 *
	 * @param request
	 * @return
	 */
	@Override
	public int updateByPrimaryKeySelective(PurchaseContract request){
		try {
			log.info("修改记录");
			PurchaseContract param = new PurchaseContract();
			BeanUtils.copyProperties(request, param);
			int flag = mapper.updateByPrimaryKeySelective(param);
	        if (flag == 1) {
	         return 1;
	        }else {
	          throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
	        }
		} catch (Exception e) {
			log.error("修改记录失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改记录失败");
		}

	}

	/**
	 * 记录详情
	 *
	 * @param request 查询的入参实体类
	 * @return 数据库查询到的实体类
	 */
	@Override
	public PurchaseContract getByPrimaryKey(PurchaseContract request) {
		return mapper.selectByPrimaryKey(request.getId());
	}


	/**
	 * 分页查询
	 *
	 * @param request 分页查询入参实体类
	 * @return 含有分页信息的实体类列表
	 */
	@Override
	public PageResult<PurchaseContract> listPageBySelective(PurchaseContract request, int pageNum, int pageSize) {
	PageHelper.startPage(pageNum, pageSize);
	PageHelper.orderBy(" create_time desc");
	List<PurchaseContract> list = mapper.listPageBySelective(request);
	PageInfo pageInfo = new PageInfo(list);
	PageResult<PurchaseContract> result = new PageResult<>();
	result.setTotal(pageInfo.getTotal());
	result.setRows(list);
	return result;
	}

	/**
	 * 不分页查询
	 *
	 * @param request 不分页查询入参实体类
	 * @return 数据库查到的实体类列表
	 */
	@Override
	public List<PurchaseContract> listAllRecord(PurchaseContract request) {
		//分页处理
		request.setDeleteFlag(0);
		return mapper.selectBySelective(request);
	}

	@Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<Boolean> updatePurchaseContract(UpdatePurchaseContractRequest request) {
        try {
            PurchaseContract purchaseContract = request.getPurchaseContract();

            //删除所有关联表
            contractAnnexMapper.deleteByContractId(purchaseContract.getId());
            contractCostMapper.deleteByContractId(purchaseContract.getId());
            contractPersonMapper.deleteByContractId(purchaseContract.getId());
            //TODO 缺少方法
//            contractStoreMapper.deleteByContractId(purchaseContract.getId());

            //更新基本信息
            mapper.updateByPrimaryKey(purchaseContract);

            //插入关联表
            if(CollectionUtils.isNotEmpty(request.getContractAnnexList())){
                contractAnnexMapper.insertBatch(request.getContractAnnexList(),purchaseContract.getId());
            }
            if (CollectionUtils.isNotEmpty(request.getContractCostList())){
                contractCostMapper.insertBatch(request.getContractCostList(),purchaseContract.getId());
            }
            if(CollectionUtils.isNotEmpty(request.getContractPersonList())){
                contractPersonMapper.insertBatch(request.getContractPersonList(),purchaseContract.getId());
            }
			//TODO 缺少方法
//            if(CollectionUtils.isNotEmpty(request.getContractStoreList())){
//                contractStoreMapper.insertBatch(request.getContractStoreList(),purchaseContract.getId());
//            }
            return RestResult.success(true);
        }catch (Exception e){
            log.error("编辑失败===>>>{}",e);
            return RestResult.error("9999","服务器错误");
        }
    }

    @Override
    public RestResult<QueryInfoPurchaseContractResponse> queryInfoPurchaseContract(PurchaseContractRequest request) {
        try {
            QueryInfoPurchaseContractResponse queryInfoPurchaseContractResponse = new QueryInfoPurchaseContractResponse();
            //查询基本信息
            PurchaseContract purchaseContract = mapper.selectByPrimaryKey(request.getId());
            queryInfoPurchaseContractResponse.setPurchaseContract(purchaseContract);
            List<ContractAnnex> contractAnnexList = contractAnnexMapper.queryListByContractId(purchaseContract.getId());
            List<ContractCost> contractCostList = contractCostMapper.queryListByContractId(purchaseContract.getId());
            List<ContractPerson> contractPersonList = contractPersonMapper.queryListByContractId(purchaseContract.getId());
			//TODO 缺少方法
//            List<ContractStore> contractStoreList = contractStoreMapper.queryListByContractId(purchaseContract.getId());
            queryInfoPurchaseContractResponse.setContractAnnexList(contractAnnexList);
            queryInfoPurchaseContractResponse.setContractCostList(contractCostList);
            queryInfoPurchaseContractResponse.setContractPersonList(contractPersonList);
//            queryInfoPurchaseContractResponse.setContractStoreList(contractStoreList);
            return RestResult.success(queryInfoPurchaseContractResponse);
        }catch (Exception e) {
            log.error("查询失败===>>>>{}",e);
            return RestResult.error("9999","查询失败");
        }
    }


}
